package com.example.yls.demoa;

import android.app.Activity;
import android.app.Application;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.Toast;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.CoordType;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.ArcOptions;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.CircleOptions;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.LogoPosition;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.PolygonOptions;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.map.Stroke;
import com.baidu.mapapi.map.TextOptions;
import com.baidu.mapapi.map.UiSettings;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.model.LatLngBounds;
import com.baidu.mapapi.search.busline.BusLineResult;
import com.baidu.mapapi.search.busline.BusLineSearch;
import com.baidu.mapapi.search.busline.BusLineSearchOption;
import com.baidu.mapapi.search.busline.OnGetBusLineSearchResultListener;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiBoundSearchOption;
import com.baidu.mapapi.search.poi.PoiCitySearchOption;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiDetailSearchOption;
import com.baidu.mapapi.search.poi.PoiDetailSearchResult;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiNearbySearchOption;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.baidu.mapapi.search.route.BikingRouteResult;
import com.baidu.mapapi.search.route.DrivingRouteLine;
import com.baidu.mapapi.search.route.DrivingRoutePlanOption;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.IndoorRouteResult;
import com.baidu.mapapi.search.route.MassTransitRouteLine;
import com.baidu.mapapi.search.route.MassTransitRoutePlanOption;
import com.baidu.mapapi.search.route.MassTransitRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteLine;
import com.baidu.mapapi.search.route.TransitRoutePlanOption;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteLine;
import com.baidu.mapapi.search.route.WalkingRoutePlanOption;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.baidu.mapapi.search.sug.OnGetSuggestionResultListener;
import com.baidu.mapapi.search.sug.SuggestionResult;
import com.baidu.mapapi.search.sug.SuggestionSearch;
import com.baidu.mapapi.search.sug.SuggestionSearchOption;

import java.util.ArrayList;
import java.util.List;


import overlayutil.BusLineOverlay;
import overlayutil.DrivingRouteOverlay;
import overlayutil.MassTransitRouteOverlay;
import overlayutil.TransitRouteOverlay;
import overlayutil.WalkingRouteOverlay;

import static android.content.ContentValues.TAG;

public class MainActivity extends Activity {
    private MapView mMapView = null;
    private BaiduMap mBaiduMap;
    private LocationClient mLocationClient;
    private BaiduMap mbaiduMap;
    private Button btnBaiMap1;
    private Button btnBaiMap2;
    private Button btnBaiMap3;
    private Button btnBaiMap4;
    private Button btnBaiMap5;
    private Button btnBaiMap6;
    private Button btnBaiMap7;
    private Button btnBaiMap8;
    private Button btnBaiMap9;
    private Button btnBaiMap10;
    private LatLng mlatLng;
    private AutoCompleteTextView autoctv;
    private SuggestionSearch suggestionSearch;
    private String key;
    private TextWatcher textWatcher;
    private RoutePlanSearch routePlanSearch;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnBaiMap1 = findViewById(R.id.btn_baiduMap1);
        btnBaiMap2 = findViewById(R.id.btn_baiduMap2);
        btnBaiMap3 = findViewById(R.id.btn_baiduMap3);
        btnBaiMap4 = findViewById(R.id.btn_baiduMap4);
        btnBaiMap5 = findViewById(R.id.btn_baiduMap5);
        btnBaiMap6 = findViewById(R.id.btn_baiduMap6);
        btnBaiMap7 = findViewById(R.id.btn_baiduMap7);
        btnBaiMap8 = findViewById(R.id.btn_baiduMap8);
        btnBaiMap9 = findViewById(R.id.btn_baiduMap9);
        btnBaiMap10 = findViewById(R.id.btn_baiduMap10);
        autoctv = findViewById(R.id.autoctv);
//        ArrayList<String> strList = new ArrayList<>();
//        strList.add("广东交通职业技术学院1");
//        strList.add("广东交通职业技术学院2");
//        strList.add("广东交通职业技术学院3");
//        strList.add("广东交通职业技术学院4");
//        strList.add("广东交通职业技术学院5");
//        strList.add("广东交通职业技术学院6");
//
//        ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,
//                android.R.layout.simple_list_item_1, strList);
//        autoctv.setAdapter(adapter);

        suggestionSearch = SuggestionSearch.newInstance();
        suggestionSearch.setOnGetSuggestionResultListener(new OnGetSuggestionResultListener() {
            @Override
            public void onGetSuggestionResult(SuggestionResult suggestionResult) {
                List<SuggestionResult.SuggestionInfo> suggestions = suggestionResult.getAllSuggestions();
                ArrayList<String> strList = new ArrayList<>();
                for (int i = 0; i < suggestions.size(); i++) {
                    Log.e(TAG, suggestions.get(i).toString());
                    strList.add(suggestions.get(i).getKey());
                }

                ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,
                        android.R.layout.simple_list_item_1, strList);
                autoctv.setAdapter(adapter);
                autoctv.removeTextChangedListener(textWatcher);
                autoctv.setText(key);
                autoctv.setSelection(key.length());
                autoctv.addTextChangedListener(textWatcher);

            }
        });
//        mMapView = (MapView) findViewById(R.id.bmapView);


        routePlanSearch = RoutePlanSearch.newInstance();
        routePlanSearch.setOnGetRoutePlanResultListener(new OnGetRoutePlanResultListener() {
            //步行
            @Override
            public void onGetWalkingRouteResult(WalkingRouteResult walkingRouteResult) {

                WalkingRouteLine line = walkingRouteResult.getRouteLines().get(0);
                WalkingRouteOverlay overlay = new WalkingRouteOverlay(mBaiduMap);
                overlay.setData(line);
                overlay.addToMap();
                overlay.zoomToSpan();
            }

            //公交
            @Override
            public void onGetTransitRouteResult(TransitRouteResult transitRouteResult) {
                TransitRouteLine line = transitRouteResult.getRouteLines().get(0);
                TransitRouteOverlay overlay = new TransitRouteOverlay(mBaiduMap);
                overlay.setData(line);
                overlay.addToMap();
                overlay.zoomToSpan();

            }

            //地铁
            @Override
            public void onGetMassTransitRouteResult(MassTransitRouteResult massTransitRouteResult) {
                MassTransitRouteLine line = massTransitRouteResult.getRouteLines().get(0);
                MassTransitRouteOverlay overlay = new MassTransitRouteOverlay(mBaiduMap);
                overlay.setData(line);
                overlay.addToMap();
                overlay.zoomToSpan();

            }

            //驾车
            @Override
            public void onGetDrivingRouteResult(DrivingRouteResult drivingRouteResult) {
                DrivingRouteLine line = drivingRouteResult.getRouteLines().get(0);
                DrivingRouteOverlay overlay = new DrivingRouteOverlay(mbaiduMap);
                overlay.setData(line);
                overlay.addToMap();
                overlay.zoomToSpan();


            }

            //户外
            @Override
            public void onGetIndoorRouteResult(IndoorRouteResult indoorRouteResult) {

            }

            @Override
            public void onGetBikingRouteResult(BikingRouteResult bikingRouteResult) {

            }
        });

//观察文字变化
        textWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                key = editable.toString();
                if (key.length() == 0) {
                    return;
                }
                suggestionSearch.requestSuggestion(new SuggestionSearchOption().city("广州").keyword(key));
            }
        };

        autoctv.addTextChangedListener(textWatcher);
        final PoiSearch poiSearch = PoiSearch.newInstance();


        btnBaiMap1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                poiSearch.searchInCity(new PoiCitySearchOption().city("广州").keyword("84"));

            }

        });


//详情
        btnBaiMap2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                poiSearch.searchPoiDetail(new PoiDetailSearchOption().poiUids("9fcc825914e5bbe303ec0137"));

            }
        });

        //周边
        btnBaiMap3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                poiSearch.searchNearby(new PoiNearbySearchOption().location(mlatLng)
                        .keyword("美食")
                        .radius(1000));

            }
        });

        //区域
        btnBaiMap4.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                LatLngBounds latLngBounds = new LatLngBounds.Builder()
                        .include(new LatLng(mlatLng.latitude + 0.05, mlatLng.longitude - 0.05))
                        .include(new LatLng(mlatLng.latitude - 0.05, mlatLng.longitude + 0.05))
                        .build();

                poiSearch.searchInBound(new PoiBoundSearchOption()
                        .bound(latLngBounds)
                        .keyword("学校"));


            }
        });

        btnBaiMap5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {


                suggestionSearch.requestSuggestion(new SuggestionSearchOption()
                        .city("广州")
                        .keyword("交通"));

            }
        });
//公交详情
        btnBaiMap6.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                BusLineSearch busLineSearch = BusLineSearch.newInstance();
                busLineSearch.setOnGetBusLineSearchResultListener(new OnGetBusLineSearchResultListener() {
                    @Override
                    public void onGetBusLineResult(BusLineResult busLineResult) {
                        Log.e(TAG, busLineResult.toString());
                        BusLineOverlay overlay = new BusLineOverlay(mBaiduMap);
                        overlay.setData(busLineResult);
                        overlay.addToMap();
                        overlay.zoomToSpan();
                    }
                });
                busLineSearch.searchBusLine(new BusLineSearchOption().city("广州")
                        .uid("14a10620d139f925c8291551"));
            }
        });

//步行路线
        btnBaiMap7.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                PlanNode start = PlanNode.withLocation(new LatLng(23.189030027099538, 113.35955277936515));
                PlanNode end = PlanNode.withLocation(new LatLng(21.704190374568253, 110.65400031308688));
                routePlanSearch.walkingSearch(new WalkingRoutePlanOption().from(start).to(end));
            }
        });


//公交路线
        btnBaiMap8.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PlanNode start = PlanNode.withLocation(new LatLng(23.189030027099538, 113.35955277936515));
                PlanNode end = PlanNode.withLocation(new LatLng(23.195914583117613, 113.37228176843733));
                routePlanSearch.transitSearch(new TransitRoutePlanOption().from(start).to(end).city("广州"));
            }
        });
//驾车导航
        btnBaiMap9.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PlanNode start = PlanNode.withLocation(new LatLng(23.189030027099538, 113.35955277936515));
                PlanNode end = PlanNode.withLocation(new LatLng(24.195914583117613, 114.37228176843733));
                routePlanSearch.drivingSearch(new DrivingRoutePlanOption().from(start).to(end).currentCity("广州"));
            }
        });


//地铁路线
        btnBaiMap10.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PlanNode start = PlanNode.withLocation(new LatLng(23.189030027099538, 113.35955277936515));
                PlanNode end = PlanNode.withLocation(new LatLng(23.14076994788187, 113.30302241364092));
                routePlanSearch.masstransitSearch(new MassTransitRoutePlanOption().from(start).to(end));
            }
        });
        poiSearch.setOnGetPoiSearchResultListener(new OnGetPoiSearchResultListener() {
            @Override
            public void onGetPoiResult(PoiResult poiResult) {
                List<PoiInfo> poiInfos = poiResult.getAllPoi();
                for (int i = 0; i < poiInfos.size(); i++) {
                    Log.e(TAG, poiInfos.get(i).toString());
                }

                //创建PoiOverlay对象
                PoiOverlay poiOverlay = new PoiOverlay(mBaiduMap);

                //设置Poi检索数据
                poiOverlay.setData(poiResult);

                //将poiOverlay添加至地图并缩放至合适级别
                poiOverlay.addToMap();
                poiOverlay.zoomToSpan();
            }


            @Override
            public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {

            }

            //搜索详情
            @Override
            public void onGetPoiDetailResult(PoiDetailSearchResult poiDetailSearchResult) {
                Log.e(TAG, poiDetailSearchResult.getPoiDetailInfoList().get(0).toString());
            }

            @Override
            public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {

            }
        });


        mMapView = (MapView) findViewById(R.id.bmapView);
        mbaiduMap = mMapView.getMap();

        mMapView.setLogoPosition(LogoPosition.logoPostionleftBottom);
        mbaiduMap.setPadding(20, 20, 20, 20);

//
//        mUiSettings = mBaiduMap.getUiSettings();
////通过设置enable为true或false 选择是否显示指南针
//        mUiSettings.setCompassEnabled(false);
        mBaiduMap = mMapView.getMap();


//普通地图 ,mBaiduMap是地图控制器对象
        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
        mBaiduMap.setMyLocationEnabled(true);

//        初始定位
//        MyLocationConfiguration myLocationConfiguration = new MyLocationConfiguration(
//                MyLocationConfiguration.LocationMode.FOLLOWING, true, BitmapDescriptorFactory
//                .fromResource(R.drawable.local), 0xAAFFFF88, 0xAA00FF00
//        );
//        mBaiduMap.setMyLocationConfiguration(myLocationConfiguration);

//        mMapView = (MapView) findViewById(R.id.bmapView);
//        mBaiduMap = mMapView.getMap();
////卫星地图
//        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_SATELLITE);

//        mMapView = (MapView) findViewById(R.id.bmapView);
//        mBaiduMap = mMapView.getMap();
////开启交通图
//        mBaiduMap.setTrafficEnabled(true);

//        mMapView = (MapView) findViewById(R.id.bmapView);
//        mBaiduMap = mMapView.getMap();
////开启热力图
//        mBaiduMap.setBaiduHeatMapEnabled(true);

        mLocationClient = new LocationClient(this);

        //通过LocationClientOption设置LocationClient相关参数
        final LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(1000);

//设置locationClientOption
        mLocationClient.setLocOption(option);

        //注册LocationListener监听器
        MyLocationListener myLocationListener = new MyLocationListener();
        mLocationClient.registerLocationListener(myLocationListener);
//开启地图定位图层
        mLocationClient.start();


        mbaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {

                drawMarker(latLng);
                Toast.makeText(MainActivity.this, "单击 维度" + latLng.latitude + "经度"
                        + latLng.longitude, Toast.LENGTH_SHORT).show();

            }

            @Override
            public boolean onMapPoiClick(MapPoi mapPoi) {
                Toast.makeText(MainActivity.this, "mapPoi 单击" + mapPoi.getName() + "坐标"
                        + mapPoi.getPosition().toString(), Toast.LENGTH_SHORT).show();
                return false;
            }
        });

//        双击
        mbaiduMap.setOnMapDoubleClickListener(new BaiduMap.OnMapDoubleClickListener() {
            @Override
            public void onMapDoubleClick(LatLng latLng) {

                mlatLng = latLng;
                Log.e(TAG, "mlatLng: " + mlatLng);

                //绘制矩形
//                drawRect(latLng);
//
//                mlatLng = latLng;
//
//     //绘制Marker
//                drawMarker(latLng);
//
//
//     //绘制弧线
//
//                drawArc(latLng);

                //绘制圆形

//                drawCircle(latLng);

                //绘制文字

//                drawText(latLng);
                //绘制信息窗
                drawInfoWindow(latLng);


//                OverlayOptions overlayOptions = new PolygonOptions()


                Toast.makeText(MainActivity.this, "双击击 维度" + latLng.latitude + "经度"
                        + latLng.longitude, Toast.LENGTH_SHORT).show();
            }
        });

//        长按
        mbaiduMap.setOnMapLongClickListener(new BaiduMap.OnMapLongClickListener() {
            @Override
            public void onMapLongClick(LatLng latLng) {
                drawInfoWindow(latLng);
                mlatLng = latLng;

                LatLng point = latLng;

                BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.drawable.loc);
                OverlayOptions options = new MarkerOptions()
                        .title("标题")
                        .position(point)
                        .icon(bitmap);

                mBaiduMap.addOverlay(options);


            }
        });

        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                Toast.makeText(MainActivity.this, marker.getTitle(), Toast.LENGTH_SHORT).show();
                return false;
            }
        });


    }

    private void drawInfoWindow(LatLng latLng) {

        Button button = new Button(getApplicationContext());
        button.setBackgroundResource(R.drawable.marker);
        button.setText("InfoWindow");

        InfoWindow infoWindow = new InfoWindow(button, latLng, -100);

        mBaiduMap.showInfoWindow(infoWindow);


    }

    private void drawText(LatLng latLng) {
        LatLng llText = latLng;

        OverlayOptions mTextOptions = new TextOptions()
                .text("百度地图SDK")
                .bgColor(0xAAFFFF00)
                .fontColor(0xAAFFFF00)
                .fontSize(24)
                .rotate(-90)
                .position(llText);

        mBaiduMap.addOverlay(mTextOptions);


    }

    private void drawCircle(LatLng latLng) {
        LatLng center = latLng;

        CircleOptions mCircleOptions = new CircleOptions().center(center)
                .radius(1200)
                .stroke(new Stroke(5, 0xAAFF0000));
        mBaiduMap.addOverlay(mCircleOptions);


    }


    private void drawMarker(LatLng latLng) {
        LatLng p1 = latLng;
        LatLng p2 = new LatLng(p1.latitude, p1.longitude);
//        LatLng p3 = new LatLng(p1.latitude,p1.longitude+0.04);
//构建Marker图标
        BitmapDescriptor bitmap = BitmapDescriptorFactory
                .fromResource(R.drawable.marker);
//构建MarkerOption，用于在地图上添加Marker
        OverlayOptions option = new MarkerOptions()
                .title("标题")
                .position(p2)
                .icon(bitmap);
//在地图上添加Marker，并显示
        mBaiduMap.addOverlay(option);

    }

    //绘制弧线
    private void drawArc(LatLng latLng) {
        LatLng p1 = latLng;
        LatLng p2 = new LatLng(p1.latitude - 0.02, p1.longitude + 0.02);
        LatLng p3 = new LatLng(p1.latitude, p1.longitude + 0.04);
        OverlayOptions marcoverlayOptions = new ArcOptions()
                .width(10)
                .color(Color.BLUE)
                .points(p1, p2, p3);
        mBaiduMap.addOverlay(marcoverlayOptions);

    }

    //    描绘矩形
    private void drawRect(LatLng latLng) {
        LatLng p1 = latLng;
        LatLng p2 = new LatLng(p1.latitude - 0.05, p1.longitude);
        LatLng p3 = new LatLng(p1.latitude - 0.05, p1.longitude + 0.05);
        LatLng p4 = new LatLng(p1.latitude, p1.longitude + 0.05);

        List<LatLng> points = new ArrayList<LatLng>();
        points.add(p1);
        points.add(p2);
        points.add(p3);
        points.add(p4);
        points.add(p1);
        OverlayOptions mOverlayOptions = new PolylineOptions()
                .width(10)
                .color(0xAAFF0000)
                .points(points);

        mBaiduMap.addOverlay(mOverlayOptions);


    }

    //构造地图数据
//    我们通过继承抽象类BDAbstractListener并重写其onReceieveLocation方法来获取定位数据，并将其传给MapView。
    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            //mapView 销毁后不在处理新接收的位置
            if (location == null || mMapView == null) {
                return;
            }
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(location.getDirection()).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            mBaiduMap.setMyLocationData(locData);
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mMapView.onResume();

    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mMapView.onPause();
    }

    @Override
    protected void onDestroy() {

        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理

        mLocationClient.stop();
        mBaiduMap.setMyLocationEnabled(false);
        mMapView.onDestroy();
        mMapView = null;
        super.onDestroy();
    }
}
